package protocol

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"os"
	"time"

	"gitee.com/LangHuaHuachihua/cloud-gin-manager/utils"
	"gitee.com/LangHuaHuachihua/cloud-gin-manager/server"
	"github.com/gin-gonic/gin"
)

func NewHttpService() *HttpService {
	//router实例但还没加载路由handlerr
	gin.SetMode(os.Getenv("GIN_MODE"))
	//路由注册
	r := server.NewRouter()
	//灵活使用handler 不限制于框架
	server := &http.Server{
		ReadHeaderTimeout: 60 * time.Second,
		ReadTimeout:       60 * time.Second,
		WriteTimeout:      60 * time.Second,
		IdleTimeout:       60 * time.Second,
		MaxHeaderBytes:    1 << 20, // 1M
		Addr:              os.Getenv("SERVER_IP"),
		Handler:           r, //指定框架路由
	}

	return &HttpService{
		server: server,
		l:     	*utils.Log(),
		r:      r,
	}
}

type HttpService struct {
	server *http.Server
	l      utils.Logger
	r      gin.IRouter
}

func (s *HttpService) Start() error {
	//gin注册的所有handler
	if err := s.server.ListenAndServe(); err != nil {
		if errors.Is(err, http.ErrServerClosed) {
			s.l.Info("server stoped \n")
			return nil
		}
		return fmt.Errorf("start service error %s \n", err.Error())
	}

	return nil
}

func (s *HttpService) Stop() error {
	s.l.Info("stop httpservice ...... \n")
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	if err := s.server.Shutdown(ctx); err != nil {
		s.l.Warning("stop httpservice error %s \n", err)
	}
	return nil
}
